package com.ruoyi.web.controller.tool;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.BuzMember;
import com.ruoyi.system.service.IBuzMemberService;


import cn.hutool.core.date.DateUtil;

@RequestMapping("/wx")
@Controller
public class WxController extends BaseController{
	
    
    @Autowired
    private IBuzMemberService buzMemberService;
    

	
	@GetMapping("auth")
	public String wxAuth(String code,String state) {
		System.out.println(code);
		System.out.println(state);
		
		// 获取微信相关信息
		//String appID = "wxef2a4572cba58836";//飞标科技
		//String appsecret = "58a439eb2ad6c0694cf43c2369588591";
		
		//飞标科技
		/*
		String appID = "wxf6b781eb9bd0d9cd";
		String appsecret = "5b3e971b47e1f16533f4a75888399b5d";
		*/
		
		//植物园
				String appID = "wx63f3c4d9b2a5762f";
				String appsecret = "e0b733b036f7da675bb1ca1c2f059f74";
		
		//String appID = "wxe92cf6f3e91bfbf7";
		//String appsecret = "e5752bfe7764bc3c54838db00861d2ff";
		String access_token = "";
		String grant_type = "client_credential";//获取access_token填写client_credential
		//这个url链接地址和参数皆不能变
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appID + "&secret=" + appsecret;

		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串：" + demoJson);
			access_token = demoJson.getString("access_token");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}
		
		//根据code获取微信用户openid
		
		
		String sns_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appID+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		String sns_token="";
		String openid="";
		try {
			URL urlGet = new URL(sns_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串2：" + demoJson);
			sns_token = demoJson.getString("access_token");
			openid = demoJson.getString("openid");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}
		
		String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+sns_token+"&openid="+openid+"&lang=zh_CN";
		
		String nickname = "";
		String headimgurl = "";
		try {
			URL urlGet = new URL(user_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串3：" + demoJson);
			nickname = demoJson.getString("nickname");
			headimgurl = demoJson.getString("headimgurl");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}
		
		//System.out.println("nickname:"+nickname); 
		//System.out.println("headimgurl:"+headimgurl);
		//System.out.println("openid:"+openid);
		// 判断userid是否存在，不存在则新增，存在，则获取信息 openid作为用户的登录名和密码，昵称则为用户名称
		/*
		SysUser user = new SysUser();
		user.setUserName(openid);
		user.setNickName(nickname);
		user.setAvatar(headimgurl);
		System.out.println(openid);
		if(userService.checkUserNameUnique(user)) {
			// 不存在则新增，存在则获取
			user.setPassword(SecurityUtils.encryptPassword(openid));
			int i = userService.insertUser(user);
			
		}
		*/
		//SysUser sysuser = userService.selectUserByUserName(openid);
		//System.out.println(sysuser.toString());
		//String token = wxService.getTokenByOpenId(openid);
		return "redirect:"+state;		
	}
	// wx/auth2
	@GetMapping("auth2")
	@ResponseBody
	public JSONObject wxAuth(String code) {
		System.out.println("===========code==========="+code);
		
		// 获取微信相关信息
		//植物园
		//String appID = "wx63f3c4d9b2a5762f";
		//String appsecret = "100f312b932acde34c8fcb0911064b2b";
		String appID = "wx63f3c4d9b2a5762f";
		String appsecret = "e0b733b036f7da675bb1ca1c2f059f74";
		/* 飞标科技
		String appID = "wxef2a4572cba58836";
		String appsecret = "58a439eb2ad6c0694cf43c2369588591";
		*/
		//String appID = "wxe92cf6f3e91bfbf7";
		//String appsecret = "e5752bfe7764bc3c54838db00861d2ff";
		String access_token = "";
		String grant_type = "client_credential";//获取access_token填写client_credential
		//这个url链接地址和参数皆不能变
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appID + "&secret=" + appsecret;

		
		logger.info("---------- start wxcode-----------"+DateUtil.now());
		
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串：" + demoJson);
			access_token = demoJson.getString("access_token");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
			e.printStackTrace();
		}
		logger.info("---------- end wxcode-----------"+DateUtil.now());
		//根据code获取微信用户openid
		
		
		String sns_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appID+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		String sns_token="";
		String openid="";
		
		logger.info("---------- start openid-----------"+DateUtil.now());
		
		try {
			URL urlGet = new URL(sns_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			if(demoJson.containsKey("errcode")) {
				//获取用户openid出错
			}
			System.out.println("JSON字符串2：" + demoJson);
			sns_token = demoJson.getString("access_token");
			openid = demoJson.getString("openid");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}
		
		logger.info("---------- end openid-----------"+DateUtil.now());
		
		
		
		//该方法需要关注公众号
		String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+sns_token+"&openid="+openid+"&lang=zh_CN";
		
		//String user_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appID+"&redirect_uri=fkh5.gxjiankang.cn&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		
		String nickname = "";
		String headimgurl = "";
		
		logger.info("---------- start nickname-----------"+DateUtil.now());
		
		try {
			URL urlGet = new URL(user_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串3：" + demoJson);
			nickname = demoJson.getString("nickname");
			headimgurl = demoJson.getString("headimgurl");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
			e.printStackTrace();
		}
		
		logger.info("---------- end nickname-----------"+DateUtil.now());
		
		//System.out.println("nickname:"+nickname); 
		//System.out.println("headimgurl:"+headimgurl);
		//System.out.println("openid:"+openid);
		// 判断userid是否存在，不存在则新增，存在，则获取信息 openid作为用户的登录名和密码，昵称则为用户名称
		/*
		SysUser user = new SysUser();
		user.setUserName(openid);
		user.setNickName(nickname);
		user.setAvatar(headimgurl);
		System.out.println(openid);
		if(userService.checkUserNameUnique(user)) {
			// 不存在则新增，存在则获取
			user.setPassword(SecurityUtils.encryptPassword(openid));
			int i = userService.insertUser(user);
			
		}
		*/
		//SysUser sysuser = userService.selectUserByUserName(openid);
		//System.out.println(sysuser.toString());
		//String token = wxService.getTokenByOpenId(openid);
		JSONObject json = new JSONObject();
		//json.put("token", token);
		
		logger.info("---------- start save member-----------"+DateUtil.now());
		if(openid!=null) {
			BuzMember member=new BuzMember();
	    	member.setOpenId(openid);
	    	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(member);
	    	if(memberList!=null&&memberList.size()>0) {
	    		member=memberList.get(0);
	    		
	    		json.put("openid", openid);
	    		json.put("headimgurl", member.getAvatar());
	    		json.put("nickname", member.getMemberName());
	    	}else {
	    		member.setOpenId(openid);
	    		member.setAvatar(headimgurl);
	    		member.setMemberName(nickname);
	    		member.setId(openid);
	    		System.out.println("-----member.openId="+member.getOpenId()+";member.Id="+member.getId());
	    		buzMemberService.insertBuzMember(member);
	    		//System.out.println("-------------------------------");
	    		
	    		json.put("openid", openid);
	    		json.put("headimgurl", headimgurl);
	    		json.put("nickname", nickname);
	    	}
		}
    	
    	logger.info("---------- end save member-----------"+DateUtil.now());
		return json;		
	}
	
	

	
	
}
